<script setup lang="ts">
  import {
    ElDropdown,
    ElDropdownMenu,
    ElDropdownItem,
    ElIcon,
    ElTable,
    ElTableColumn,
    TableInstance,
    ElMessageBox,
  } from 'element-plus'
  import { ArrowDown } from '@element-plus/icons-vue'
  import Pagination from '@/components/Pagination/index.vue'
  import DetectFieldConnectModal from './DetectFieldConnectModal.vue'
  import { ref } from 'vue'
  import {
    useGetModuleDetectFieldList,
    useModuleDetectFieldDelByIds,
    useModuleDetectFieldMobileHide,
    useModuleDetectFieldMobileShow,
    useModuleDetectFieldRequired,
    useModuleDetectFieldUnRequired,
  } from '@/services/pages/return-factory/useModule'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { MultipleOperateType } from './types'

  const { total, fieldList, getFieldListParams, getFieldListLoading, getFieldList } =
    useGetModuleDetectFieldList()
  const { del } = useModuleDetectFieldDelByIds()
  const { updateToUnMobileShow } = useModuleDetectFieldMobileShow()
  const { updateToUnMobileHide } = useModuleDetectFieldMobileHide()
  const { updateToRequired } = useModuleDetectFieldRequired()
  const { updateToUnRequired } = useModuleDetectFieldUnRequired()

  defineOptions({
    name: 'ReturnFactoryModuleDetectFieldConnect',
  })

  const props = defineProps({
    moduleId: {
      type: String,
      required: true,
    },
  })

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 检测字段关联弹窗显示状态
  const detectFieldConnectModalVisible = ref(false)

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 正在编辑的字段id
  const editingDetectFieldConnectId = ref('')

  // 字段选择列表
  const fieldSelectList = ref<Array<string>>([])

  // 批量操作方法映射
  const multipleOperateFn = ref({
    mobileShow: updateToUnMobileShow,
    mobileHide: updateToUnMobileHide,
    required: updateToRequired,
    unRequired: updateToUnRequired,
    del: del,
  })

  /**
   * 获取列表
   */
  const getList = () => {
    if (paginationInstance.value) {
      getFieldListParams.value.limit = paginationInstance.value.size
      getFieldListParams.value.page = paginationInstance.value.current
      getFieldList(props.moduleId)
    }
  }

  /**
   * 编辑事件
   */
  const handleEdit = (id: string) => {
    editingDetectFieldConnectId.value = id
    detectFieldConnectModalVisible.value = true
  }

  /**
   * 表格删除按钮点击事件
   * @param {ReturnFactoryDetectCustomField} detectFieldConnect - 检测字段关联对象
   */
  const handleDel = (detectFieldConnect: ReturnFactoryDetectCustomField) => {
    if (tableInstance.value) {
      tableInstance.value.toggleRowSelection(detectFieldConnect, true)
      ElMessageBox({
        title: '提示',
        message: '确定要删除该字段吗？',
        type: 'error',
        autofocus: false,
        showCancelButton: true,
        async beforeClose(action, instance, done) {
          if (['cancel', 'close'].includes(action)) {
            done()
            return
          }

          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.cancelButtonLoading = true
            const res = await del(fieldSelectList.value)
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
            if (res.code === 20000) {
              HMessage.success('字段删除成功')
              done()
              getList()
              return
            }
            HMessageBox.error(res.message)
          }
        },
      })
    }
  }

  /**
   * 字段选择事件
   * @param {Array<ReturnFactoryDetectCustomField>} fieldList - 选择的列表
   */
  const handleSelectionChange = (fieldList: Array<ReturnFactoryDetectCustomField>) => {
    fieldSelectList.value = fieldList.map((item) => item.id)
  }

  /**
   * 获取批量操作弹出框提示
   * @param {MultipleOperateType} type - 操作类型
   */
  const getMultipleOperateMsgOption = (type: MultipleOperateType) => {
    if (type === 'mobileShow') {
      return '确定要移动端显示选择的字段'
    }
    if (type === 'mobileHide') {
      return '确定要移动端隐藏选择的字段'
    }
    if (type === 'required') {
      return '确定要将选择的字段修改为必填'
    }
    if (type === 'unRequired') {
      return '确定要将选择的字段修改为不必填'
    }
    if (type === 'del') {
      return '确定删除选择的字段'
    }
  }

  /**
   * 批量操作
   * @param {MultipleOperateType} type - 操作类型
   */
  const multipleOperate = (type: MultipleOperateType) => {
    ElMessageBox({
      title: '提示',
      message: getMultipleOperateMsgOption(type),
      showCancelButton: true,
      autofocus: false,
      type: type === 'del' ? 'error' : 'warning',
      async beforeClose(action, instance, done) {
        if (['close', 'cancel'].includes(action)) {
          done()
          return
        }

        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          const res = await multipleOperateFn.value[type](fieldSelectList.value)
          instance.confirmButtonLoading = false
          instance.cancelButtonLoading = false
          if (res.code === 20000) {
            HMessage.success('更新成功')
            getList()
            done()
            return
          }
          HMessageBox.error(res.message)
        }
      },
    })
  }

  defineExpose({
    getList,
  })
</script>

<template>
  <div v-loading="getFieldListLoading" class="return-factory-module-detect-field-connect">
    <div class="header">
      <h-plain-button @click="detectFieldConnectModalVisible = true">关联检测字段</h-plain-button>
      <el-dropdown trigger="click">
        <h-button :disabled="fieldSelectList.length === 0">
          批量操作
          <el-icon>
            <arrow-down></arrow-down>
          </el-icon>
        </h-button>

        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="multipleOperate('required')">批量必填</el-dropdown-item>
            <el-dropdown-item @click="multipleOperate('unRequired')">批量不必填</el-dropdown-item>
            <el-dropdown-item @click="multipleOperate('mobileShow')"
              >批量移动端显示</el-dropdown-item
            >
            <el-dropdown-item @click="multipleOperate('mobileHide')"
              >批量移动端隐藏</el-dropdown-item
            >
            <el-dropdown-item @click="multipleOperate('del')">批量删除</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="table">
      <el-table
        ref="tableInstance"
        :border="true"
        stripe
        :data="fieldList"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择 -->
        <el-table-column
          type="selection"
          width="50"
          fixed="left"
          :align="'center'"
        ></el-table-column>

        <!-- 序号 -->
        <el-table-column
          type="index"
          label="序号"
          fixed="left"
          :align="'center'"
          width="50"
        ></el-table-column>

        <!-- 关联字段名 -->
        <el-table-column
          label="关联字段名"
          min-width="100"
          prop="name"
          show-overflow-tooltip
        ></el-table-column>

        <!-- 移动端是否显示 -->
        <el-table-column label="移动端是否显示" width="120">
          <template #default="{ row }">
            {{ row.mobileShow ? '是' : '否' }}
          </template>
        </el-table-column>

        <!-- 是否必填 -->
        <el-table-column label="是否必填" width="120">
          <template #default="{ row }">
            {{ row.required ? '是' : '否' }}
          </template>
        </el-table-column>

        <!-- 创建时间 -->
        <el-table-column label="创建时间" width="140" prop="createTime"></el-table-column>

        <!-- 更新时间 -->
        <el-table-column label="更新时间" width="140" prop="updateTime"></el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <h-space>
              <h-link @click="handleEdit(row.id)">编辑</h-link>
              <h-link type="error" @click="handleDel(row)">删除</h-link>
            </h-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <pagination ref="paginationInstance" :list_total="total"></pagination>
    </div>

    <detect-field-connect-modal
      v-model:visible="detectFieldConnectModalVisible"
      :module-id="props.moduleId"
      :field-connect-id="editingDetectFieldConnectId"
      @update="getList"
    ></detect-field-connect-modal>
  </div>
</template>

<style scoped lang="scss">
  .return-factory-module-detect-field-connect {
    display: flex;
    flex-direction: column;
    row-gap: 5px;

    .header {
      display: flex;
      column-gap: 5px;
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
